<template>
	<view>
		<view class="html2canvas" :prop="domId" :change:prop="html2canvas.create">
			<span>{{img}}</span>
			<slot></slot>
		</view>
	</view>
</template>

<script>
	import {
		pathToBase64,
		base64ToPath
	} from 'image-tools';
	export default {
		name: 'html2canvas',
		props: {
			domId: {
				type: String,
				required: true
			}
		},
		data() {
			return {
				img: ''
			}
		},
		methods: {
			async renderFinish(base64) {
				console.log('64', base64)
				try {
					const imgPath = await base64ToPath(base64, '.jpeg');
					console.log(imgPath)
					this.$emit('renderFinish', imgPath);
				} catch (e) {
					//TODO handle the exception
					console.log('html2canvas error', e)
				}
			},
			showLoading() {
				uni.showLoading()
			},
			hideLoading() {
				uni.hideLoading();
			}
		}
	}
</script>

<script module="html2canvas" lang="renderjs">
	import html2canvas from 'html2canvas';
	export default {
		methods: {
			async create() {
				try {
					const timeout = setTimeout(async () => {
						const shareContent = document.getElementById('refBox1');
						// const canvas = await html2canvas(shareContent, {
						// 	width: shareContent.offsetWidth, //设置canvas尺寸与所截图尺寸相同，防止白边
						// 	height: shareContent.offsetHeight, //防止白边
						// 	logging: true,
						// 	useCORS: true
						// });
						// console.log('domId', base64)
						// const base64 = canvas.toDataURL('image/jpeg');
						// 创建一个Canvas对象
						// var canvas = document.createElement('canvas');
						// var ctx = canvas.getContext('2d');

						// // 在Canvas上绘制内容
						// ctx.fillStyle = 'red';
						// ctx.fillRect(0, 0, 200, 200);

						// // 将Canvas转换为图片
						// var imgData = canvas.toDataURL(); // 将Canvas的内容转换为base64的图像数据

						// // 创建一个Image对象
						// var img = new Image();
						// this.img = img
						// // 将base64的图像数据赋值给Image对象的src属性
						// img.src = imgData;
						// this.$ownerInstance.callMethod('renderFinish', imgData);
						// 将Image对象添加到HTML页面中显示
						// document.body.appendChild(img);
						html2canvas(shareContent, {
							dpi: 160,
							scale: 1,
							useCORS: true,
							allowTaint: false,
							taintTest: true, //是否在渲染前测试图片
							logging: false,
							letterRendering: true,
							width: shareContent.offsetWidth, //显示的canvas窗口的宽度
							height: shareContent.offsetHeight, //显示的canvas窗口的高度
						}).then((canvas,v,s) => {
							// 在微信里,可长按保存或转发
							document.body.appendChild(canvas)
							console.log("canvas", JSON.stringify(canvas));
							// canvas.getContext("2d");
							this.img = canvas.toDataURL("image/png")
							// console.log(canvas.toDataURL("image/png"));


						})
						// this.$ownerInstance.callMethod('renderFinish', base64);
						clearTimeout(timeout);
					}, 1000);
				} catch (error) {
					console.log(error)
				}
			}
		}
	}
</script>


<style lang="scss">
	.html2canvas {
		height: 100%;
		width: 100%;
	}
</style>